<template>
    <!-- draggable:可以设置拖拽 -->
    <!-- before-close:关闭前的回调，会暂停 Dialog 的关闭 -->
    <!-- append-to-body：Dialog自身是否插入至 body 元素上 -->
    <!-- destroy-on-close：当关闭 Dialog 时，销毁其中的元素 -->
    <el-dialog 
        v-model="show" 
        @close="close" 
        :title="updateRow?'修改角色' :'新增角色'" 
        width="600px" 
        draggable
        :before-close="close"
        :append-to-body="true"
        :destroy-on-close="true">
        <template #default>
            <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input placeholder="请输入角色名称" v-model="form.roleName" />
                </el-form-item>
                <el-form-item label="权限字符" prop="rolePerm">
                    <el-input placeholder="请输入权限字符" v-model="form.rolePerm" />
                </el-form-item>
                <el-form-item label="状态" prop="enabled">
                    <el-radio-group v-model="form.enabled">
                        <el-radio v-for="item in dicts.system_global_status" :key="item.v"
                            :label="form.enabled==item.v?form.enabled:item.v">
                            {{ item.k }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单权限">
                    <div class="item-menu">
                        <!-- v-model控制回调函数的e -->
                        <el-checkbox v-model="permission.openAll" @change="toggleTreeCollapse">
                            展开/折叠
                        </el-checkbox>
                        <!-- v-model控制回调函数的e -->
                        <el-checkbox v-model="permission.selectAll" @change="toggleTreeChecked">
                            全选/全不选
                        </el-checkbox>
                        <el-checkbox v-model="permission.linkage">
                            父子(联动/不联动)
                        </el-checkbox>

                        <!-- check-strictly：父子关联 -->
                        <!-- props: 变量为对象，其中label属性是树的每一项的名字 -->
                        <!-- default-expand-all：是否默认展开所有节点 -->
                        <!-- show-checkbox：节点是否可用 -->
                        <el-tree ref="menuTreeRef" class="tree" 
                            :data="permission.treeList" 
                            :props="permission.treeProps"
                            :check-strictly="!permission.linkage" 
                            :default-expand-all="permission.openAll" 
                            show-checkbox
                            default-expand-all 
                            node-key="id"  />
                    </div>
                </el-form-item>

                <el-form-item label="备注" prop="descript">
                    <el-input type="textarea" placeholder="请输入内容" v-model="form.descript" :maxlength="200"
                        show-word-limit />
                </el-form-item>
            </el-form>
        </template>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="onSubmit"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onBeforeMount } from 'vue'
import { menuTree,roleAdd,roleGet,roleUpdate } from './api'
// import { ElMessage, ElMessageBox } from 'element-plus'

// 表单数据
const form = reactive ({
    id:'',
    rolename:'',
    rolePerm:'',
    enabled:'1',
    descript:'',
})

const props = defineProps({
    show: Boolean,
    updateRow:String
})
// 显示dialog
const show = ref(props.show)
// 当前角色的id
let updateRow = ref(props.updateRow);
// 关闭dialog（取消）
const emit = defineEmits(['update:show'])
const cancel = () => {
    emit('update:show', false)
}
// 关闭dialog（x）
const close = ()=>{
    ElMessageBox.confirm('Are you sure?')
    .then(() => {
      ElMessage({type: 'success',message:'操作成功'})
      emit('update:show', false)
    })
}

// treeDom
const menuTreeRef =ref(null)

// 菜单树
let permission = reactive({
    treeList:[],
    treeProps:{
        label:'name',
    },
    linkage:true,
    openAll:false,
    selectAll:false
})

// mixin
const { proxy } = getCurrentInstance()  // getCurrentInstance是当前组件实例，proxy是当前组件实例的代理对象，用于访问和操作当前组件的属性和方法
// 生命周期
onBeforeMount(async ()=>{
    // 混入（获取字典）
    proxy.sendDicts(['system_global_status'])
    // 菜单树
    let treeData = await menuTree()
    permission.treeList = treeData.data
    // 角色详情
    if(updateRow.value){//点击修改按钮才会执行
        let roleData = await roleGet(updateRow.value)   
        let {id,roleName,rolePerm,enabled,descript} = roleData.data.role
        form.id = id
        form.rolename = roleName //角色名称
        form.rolePerm = rolePerm //角色权限编码
        form.enabled = enabled //下拉列表的value，值为1启用 0禁用
        form.descript = descript //备注
        // setCheckedKeys：设置目前选中的节点(点击修改自动选中），使用此方法必须设置node-key属性
        menuTreeRef.value.setCheckedKeys(roleData.data.permissions)
    }
    



})

// 展开/折叠
const toggleTreeCollapse = (e)=>{
    let nodeMap = menuTreeRef.value.store.nodesMap
    Object.keys(nodeMap).forEach((key)=>{
        // nodeMap[key]是每个节点
        nodeMap[key].expanded = e
    })
}

// 全选/全不选
const toggleTreeChecked = (e)=>{
    let nodeMap = menuTreeRef.value.store.nodesMap
    Object.keys(nodeMap).forEach((key)=>{
        // nodeMap[key]是每个节点
        nodeMap[key].checked = e
    })
}

// 新增
const add = async ()=>{
    let res = await roleAdd({
    // 树的id
    // getCheckedKeys()：返回当前选中节点 key 的数组
    permissionIds: menuTreeRef.value.getCheckedKeys(),
    ...form,
    })
    if( res.code =='200' ) ElMessage({type:'success',message:'添加成功'})

}

// 修改

const update = async ()=>{
    let res = await roleUpdate({
        permissionIds: menuTreeRef.value.getCheckedKeys(),
        ...form,
    })
    if( res.code =='200' ) ElMessage({type:'success',message:'修改成功'})
}

// 确认(保存)
const onSubmit = async ()=>{
    if( updateRow.value ){
        await update();
    }else{
        await add();
    }
    show.value = false
    emit('change')
}

</script>

<style scoped>
.item-menu {
  width: 100%;
}
.tree{
    margin-top: 0.5rem;
    background-color: #fff;
    border:1px solid #dcdfe6;
    border-radius: 4px;
}
</style>